#!/usr/bin/env python3

import json
import time
from pprint import pprint

import requests


def _request(url: str, data: dict, method="post") -> dict:
    data_json = json.dumps(data)
    func = getattr(requests, method)
    response = func(url, data=data_json)
    return response.json()


def request_post(url: str, data: dict) -> dict:
    return _request(url, data, "post")


def request_get(url: str, data: dict) -> dict:
    return _request(url, data, "get")


ip = "59.49.35.195"  # 服务器 IP
port = "37400"  # Python-SDK 服务的端口号

url_tmpl = "http://{}:{}/api/p/medical/blockchain/{}"
url_crate = url_tmpl.format(ip, port, "crate")
url_sign = url_tmpl.format(ip, port, "sign")
url_verify = url_tmpl.format(ip, port, "verify")
url_hash = url_tmpl.format(ip, port, "hash")
url_upload = url_tmpl.format(ip, port, "upload")
url_download = url_tmpl.format(ip, port, "download")

text = str(time.time())  # 想要上传的数据
account_password = "54953132d9162b52defef0cf7b790e3a"
pubkey = "the key"  # 自定义的公钥，这里设成 "the key"

# 区块链公私钥生成
data_crate = {"account_password": account_password, "key": pubkey}
ret = request_post(url_crate, data_crate)
address = ret["address"]
prvkey = ret["prvkey"]
print("区块链公私钥生成")
pprint(ret)

# 区块链私钥签名
data_sign = {"prvkey": prvkey, "text": text}
ret = request_post(url_sign, data_sign)
sign = ret["sign"]
print("区块链私钥签名")
pprint(ret)

# 区块链公钥验签
data_verify = {"sign": sign, "text": text, "address": address}
print("区块链公钥验签")
pprint(request_post(url_verify, data_verify))

# 区块链数据摘要
data_hash = {"text": text}
ret = request_post(url_hash, data_hash)
hash = ret["hash"]
print("区块链数据摘要")
pprint(ret)

# 数据上链
data_upload = {
    "file_hash": hash,
    "file_data": text,
    "file_pubkey": pubkey,
    "file_sign": sign,
}
ret = request_post(url_upload, data_upload)
print("数据上链")
pprint(ret)

# 数据查询
# hash = "bc54a57ffb5c86fd7b9aa6fdf715cf1e7443a475c385578778fafb3637970761"
# hash = "5f4cc5d90025275e0b67c61af83c441474f8e488b4c1fb742da2fa2676b74e4b"
# hash = "b96e1419dc9c48ee48b4489992e9ca33705ff5d1c5709cc9bfaf8767c651bdae"
# hash = "5a2800c34d56023b41c2392b9a6a3c8c5a5b9e274b1c3d83b73a249d8f3ae629"
# hash = "b70ba1ccc8358b891aa6a39e3744523d7d0a820a8d796b9235cef4b9c47ac883"
# hash = "944e5cc203a61d48d0a0a158bb32d47ab3ee7c0f1609f972ef25367fcd3cc2f5"
# hash = "ae526d7f201469f02356a83932bb48f49e6eec8423f384a602162f37c65daf8f"
# hash = "5f4cc5d90025275e0b67c61af83c441474f8e488b4c1fb742da2fa2676b74e4b"
data_download = {"file_hash": hash}
ret = request_post(url_download, data_download)
print("数据查询")
pprint(ret)
